﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace Milan.Deploy
{
	public class DirectoryWatcher : ThreadScanner
	{
		public DirectoryWatcher(Application application, string directory, NotifyFilters notifyFilters)
			: base(application)
		{
			m_directory = directory;
			if (!Directory.Exists(directory))
				Directory.CreateDirectory(directory);
			m_notifyFilters = notifyFilters;
		}
		private NotifyFilters m_notifyFilters;
		/// <summary>
		/// Blocking call: waits for a file to appear in the input directory, or for the quit event.
		/// </summary>
		/// <returns>Always returns true, because the quite event was received.</returns>
		protected override void Run()
		{
			var inPath = Path.GetFullPath(m_directory);
			FileSystemWatcher watcher = new FileSystemWatcher(inPath, "*.*");
			watcher.NotifyFilter = m_notifyFilters;
			watcher.Changed += new FileSystemEventHandler(OnChanged);
			watcher.Created += new FileSystemEventHandler(OnCreated);
			watcher.Renamed += new RenamedEventHandler(OnRenamed);
			watcher.EnableRaisingEvents = true;
			QuitEvent.WaitOne();	// Watch until the quit event is signaled
		}
		protected virtual void OnChange(string file, WatcherChangeTypes changeType)
		{

		}
		protected virtual void OnCreate(string file, WatcherChangeTypes changeType)
		{

		}
		protected virtual void OnRename(string file, WatcherChangeTypes changeType)
		{

		}
		protected string m_directory;

		/// <summary>
		/// Called indirectly from WatchTheInDirectory when a file comes in
		/// </summary>
		/// <param name="source"></param>
		/// <param name="e"></param>
		private void OnChanged(object source, FileSystemEventArgs e)
		{
			OnChange(e.FullPath, e.ChangeType);
		}

		/// <summary>
		/// Called indirectly from WatchTheInDirectory when a file comes in
		/// </summary>
		/// <param name="source"></param>
		/// <param name="e"></param>
		private void OnCreated(object source, FileSystemEventArgs e)
		{
			OnCreate(e.FullPath, e.ChangeType);
		}
		/// <summary>
		/// Called indirectly from WatchTheInDirectory when a file moves into the in directory
		/// </summary>
		/// <param name="source"></param>
		/// <param name="e"></param>
		private void OnRenamed(object source, RenamedEventArgs e)
		{
			OnRename(e.FullPath, e.ChangeType);
		}
	}
}
